package cn.wsalix.order.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.exception.NutException;
import cn.anlaser.service.impl.SimpleServiceImpl;
import cn.anlaser.utils.BeanMapper;
import cn.anlaser.utils.MD5Util;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.anlaser.utils.SignUtils;
import cn.wsalix.admin.entity.SysUser;
import cn.wsalix.admin.service.UserService;
import cn.wsalix.code.XmlMapper;
import cn.wsalix.config.AppConfig;
import cn.wsalix.constant.AlipayGlobal;
import cn.wsalix.constant.Global;
import cn.wsalix.constant.WxGlobal;
import cn.wsalix.freemarker.FreemarkerUtil;
import cn.wsalix.login.form.WxOrderForm;
import cn.wsalix.login.vo.WxPayVO;
import cn.wsalix.observable.service.BuyService;
import cn.wsalix.observable.service.PayService;
import cn.wsalix.order.entity.MasterTuan;
import cn.wsalix.order.entity.Order;
import cn.wsalix.order.entity.PayNotify;
import cn.wsalix.order.form.OrderForm;
import cn.wsalix.order.form.WeiXinNotifyForm;
import cn.wsalix.order.form.WxPayInfoForm;
import cn.wsalix.order.repository.OrderRepository;
import cn.wsalix.order.repository.PayNotifyRepository;
import cn.wsalix.order.service.OrderInfoService;
import cn.wsalix.order.service.OrderService;
import cn.wsalix.order.service.TuanService;
import cn.wsalix.order.status.OrderEnum;
import cn.wsalix.shop.entity.Price;
import cn.wsalix.shop.entity.Product;
import cn.wsalix.shop.form.PriceForm;
import cn.wsalix.shop.service.PriceService;
import cn.wsalix.shop.service.ProductService;
import cn.wsalix.shop.status.PayEnum;
import cn.wsalix.status.PriceEnum;
import cn.wsalix.status.TuanEnum;
import cn.wsalix.type.OrderTypeEnum;
import cn.wsalix.type.PayTypeEnum;
import cn.wsalix.user.entity.UserInfo;
import cn.wsalix.user.service.UserInfoService;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;
import com.thoughtworks.xstream.io.xml.XppDriver;

@Service("orderService")
public class OrderServiceImpl extends
		SimpleServiceImpl<OrderForm, OrderRepository, Order> implements
		OrderService {
	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private OrderInfoService orderInfoService;
	@Autowired
	private PayNotifyRepository payNotifyRepository;
	@Autowired
	private ProductService productService;
	@Autowired
	private TuanService masterTuanService;
	@Autowired
	private PriceService productPriceService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserInfoService userInfoService;

	@Override
	public String module() {
		return "/user/order";
	}

	@Override
	public OrderRepository getRepository() {
		return orderRepository;
	}
	@Transactional
	@Override
	public Order add(OrderForm form) {
		Order obj = null;
		if (form.getOrderId() != null && form.getOrderId() != 0) {// 团购购买
			return joinTuan(form);
		}
		if (form.getProductId() != null && form.getProductId() != 0) {// 计算折扣
			caleDiscount(form);
		}
		if (form.getPriceId() != null && form.getPriceId() != 0) {// 折扣购买或开团
			calePriceId(form);
		}
		if (form.getAmount() == null || form.getAmount() == 0) {
			throw new NutException("订单总价不能为0");
		}
		if (form.getPrice() != null) {// 计算折扣价，存在产品ID
			return calePrice(form);
		}
		return obj;
	}

	@Transactional
	private Order joinTuan(OrderForm form) {
		Order tuanMaster = orderRepository.findOne(form.getOrderId());
		if (tuanMaster == null) {
			throw new NutException("参与的团购订单[" + form.getOrderId() + "]不存在");
		}
		if (tuanMaster.getCustomer().getId() == form.getUserId()) {
			throw new NutException("您是团购[" + form.getOrderId() + "]发起人，不能重复入团");
		}

		if (tuanMaster.getOrderType().ordinal() != OrderTypeEnum.tuan.ordinal()) {
			throw new NutException("当前订单[" + form.getOrderId() + "]不是团购订单");
		} else {
			if (!tuanMaster.isMaster()) {
				throw new NutException("当前订单[" + form.getOrderId() + "]不是团购主订单");
			}
		}
		for (Order orderItem : tuanMaster.getTuanOrders()) {
			if (orderItem.getCustomer().getId() == form.getUserId()) {
				throw new NutException("您已入团[" + form.getOrderId() + "]，不能重复入团");
			}
		}
		form.setProduct(tuanMaster.getProduct());
		form.setPrice(tuanMaster.getPrice());
		form.setAmount(tuanMaster.getAmount());
		form.setNum(tuanMaster.getNum());
		Order obj = buildOrder(form);
		obj.setName("赫伯的秘密");
		// BeanMapper.map(form, getEntityClazz());
		MasterTuan masterTuan = tuanMaster.getMasterTuan();// 修改主团信息
		if (masterTuan.getTuanNum() == (masterTuan.getCurrNum() + 1)) {
			obj.setInOnNum(masterTuan.getTuanNum());
			masterTuan.setCurrNum(masterTuan.getTuanNum());
			// tuanMaster.setStatus(OrderEnum.undone);
			// tuanMaster.setTuanStatus(TuanEnum.filled);
		} else if ((masterTuan.getCurrNum() + 1) < masterTuan.getTuanNum()) {
			obj.setInOnNum(masterTuan.getCurrNum() + 1);
			masterTuan.setCurrNum(masterTuan.getCurrNum() + 1);
		} else {
			throw new NutException("团购人数已满[" + form.getOrderId() + "]，不能入团");
		}

		Order obj11 = BeanMapper.map(obj, Order.class);
		obj.setOrderType(OrderTypeEnum.tuan);
		obj.setTuan(true);
		obj.setMaster(false);

		obj.setTitle("[子]" + tuanMaster.getProduct().getName());

		obj.setPostfree(tuanMaster.getPostfree());
		obj.setAmount(tuanMaster.getAmount());
		obj.setNum(tuanMaster.getNum());
		masterTuanService.edit(masterTuan);
		obj.setMasterTuan(masterTuan);
		obj.setTuanMaster(tuanMaster);
		obj.setTuanStatus(TuanEnum.underway);
		obj = super.add(obj);
		return obj;
	}

	private Order buildOrder(OrderForm form) {
		Date dateNow = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");

		SysUser user = userService.findById(form.getUserId());
		UserInfo userInfo = userInfoService.findById(form.getUserId());

		Order obj = BeanMapper.map(form, Order.class);
		obj.setProduct(form.getProduct());
		obj.setPrice(form.getPrice());
		obj.setPostfree(form.getPostfree());
		obj.setOrderTime(dateNow);
		obj.setOrderDate(formatter.format(dateNow));
		obj.setTradeNo(getOutTradeNo());
		obj.setStatus(OrderEnum.undone);
		obj.setPay(PayEnum.unPay);
		obj.setAmount(form.getAmount());
		obj.setCustomer(user);
		obj.setUserInfo(userInfo);
		obj.setCustomerName(userInfo.getCustomerName());
		obj.setAvatar(userInfo.getAvatar());
		return obj;
	}

	@Transactional
	private Order calePrice(OrderForm form) {
		Order obj = buildOrder(form);
		obj.setName("赫伯的秘密");
		Price price = form.getPrice();
		Product product = form.getProduct();
		switch (price.getType()) {
		case discount:
			obj.setTitle("[折]" + product.getName());
			obj.setOrderType(OrderTypeEnum.discount);
			obj.setNum(price.getNum());
			return super.add(obj);
		case original:
			obj.setTitle("[原]" + product.getName());
			obj.setOrderType(OrderTypeEnum.original);
			obj.setNum(form.getNum());
			return super.add(obj);
		case tuan:
			obj.setTitle("[主]" + product.getName());

			obj.setNum(price.getNum());

			obj.setOrderType(OrderTypeEnum.tuan);
			obj.setMaster(true);
			obj.setTuan(true);
			obj.setInOnNum(1);
			obj = super.add(obj);

			MasterTuan masterTuan = openTuan(obj);
			obj.setTuanStatus(TuanEnum.underway);
			obj.setMasterTuan(masterTuan);
			obj.setTuanMaster(obj);
			return super.edit(obj);
		default:
			break;
		}
		return obj;
	}

	@Transactional
	private MasterTuan openTuan(Order obj) {
		MasterTuan masterTuan = new MasterTuan();
		masterTuan.setTuanStatus(TuanEnum.underway);
		masterTuan.setCurrNum(1);// 参团人数1
		// masterTuan.setOrderDate(obj.getOrderDate());
		masterTuan.setTuanNum(obj.getPrice().getTuanNum());
		masterTuan.setTradeNo(obj.getTradeNo());
		masterTuan.setMasterOrder(obj);
		masterTuan.setProductId(obj.getProduct().getId());
		// TODO
		/*
		 * obj.setCustomer(user); obj.setCustomerName(user.getUsername());
		 * obj.setAvatar(user.getAvatar());
		 */

		masterTuan.setCustomerName(obj.getCustomerName());
		masterTuan.setAvatar(obj.getAvatar());
		masterTuan = masterTuanService.add(masterTuan);
		return masterTuan;
	}

	private void calePriceId(OrderForm form) {
		Price price = productPriceService.findById(form.getPriceId());
		Product product = price.getProduct();
		form.setProduct(product);
		form.setPostfree(product.getPostfree());
		form.setPrice(price);
		form.setAmount(price.getNum() * price.getPrice()
				+ product.getPostfree());
		form.setDiscount(true);
	}

	private void caleDiscount(OrderForm form) {
		// 传入产品ID和数量，计算可参与的折扣
		Product product = productService.findById(form.getProductId());
		form.setProduct(product);
		if (product == null) {
			throw new NutException("您购买的商品[" + form.getProductId() + "]不存在");
		}
		if (form.getNum() < 0) {
			throw new NutException("您购买的商品[" + form.getProductId() + "]数量不能少于1");
		}
		PriceForm priceForm = new PriceForm();
		priceForm.setProductId(form.getProductId());
		// priceForm.setNum(form.getNum());
		form.setPostfree(product.getPostfree());
		List<Price> dis = productPriceService.findByForm(priceForm);
		for (Price price : dis) {
			if (price.getType().ordinal() == PriceEnum.original.ordinal()) {
				form.setPrice(price);
				form.setAmount(form.getNum() * price.getPrice()
						+ product.getPostfree());
			}
			if (price.getType().ordinal() == PriceEnum.discount.ordinal()) {
				if (price.getNum() == form.getNum()) {
					form.setPrice(price);
					form.setAmount(price.getNum() * price.getPrice()
							+ product.getPostfree());
					form.setDiscount(true);
					break;
				}
			}

		}
	}

	@Override
	public Class<Order> getEntityClazz() {
		return Order.class;
	}

	@Override
	public Map<String, SearchFilter> buildByForm(OrderForm form) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (form.getUserId() != null && form.getUserId() != 0) {
			filters.put("customer.id", new SearchFilter("customer.id",
					Operator.EQ, form.getUserId()));
		}
		if (form.getOrderId() != null && form.getOrderId() != 0) {
			filters.put("tuanMaster.id", new SearchFilter("tuanMaster.id",
					Operator.EQ, form.getOrderId()));
		}
		if (form.getOrderType() != null) {
			filters.put("orderType", new SearchFilter("orderType", Operator.EQ,
					form.getOrderType().ordinal()));
		}
		if (form.getPayType() != null) {
			filters.put("payType", new SearchFilter("payType", Operator.EQ,
					form.getPayType().ordinal()));
		}
		if (form.getPay() != null) {
			filters.put("pay", new SearchFilter("pay", Operator.EQ, form
					.getPay().ordinal()));
		}
		if (form.isTuan()) {
			filters.put("tuanMaster", new SearchFilter("tuanMaster",
					Operator.NOTNULL, null));
		}

		return filters;
	}

	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;

	@Override
	public String getPayInfoByAli(OrderForm entity) {
		String productName = "测试的商品";
		String productDesc = "该测试商品的详细描述";
		String prices = "0.01";
		/*
		 * if (entity.getId() != null && !entity.getId().equals("")) {
		 * ExActivity exActivity = exActivityService.findByOne(entity.getId());
		 * productName = exActivity.getTitle(); productDesc =
		 * exActivity.getSubTitle(); prices = "0.01"; }
		 */
		String orderInfo = getOrderInfo(productName, productDesc, prices);

		// 对订单做RSA 签名
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();
		return payInfo;
	}

	public String getSignType() {
		return "sign_type=\"RSA\"";
	}

	public String sign(String content) {
		return SignUtils.sign(content, AlipayGlobal.RSA_PRIVATE);
	}

	/**
	 * @param subject
	 * @param body
	 * @param price
	 * @return
	 */
	public String getOrderInfo(String subject, String body, String price) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + AlipayGlobal.PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + AlipayGlobal.SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + AlipayGlobal.NOTIFY_URL + "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	public String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 * 1，普通购买 a，传入产品ID、数量1=>普通购买 b，传入产品ID、数量大于1，计算可参与折扣，无折扣=>普通购买 2，折扣购买
	 * a，传入产品ID、数量大于1，计算可参与折扣，存在折扣=>折扣购买 b，传入产品价格ID，该定价为折扣定价=>折扣购买 3,团购购买
	 * a，传入产品价格ID，该定价为团购定价=>主团购购买 b，传入订单ID，该订单为主团购订单=>参与团购购买
	 */
	@Transactional
	@Override
	public void update(Observable o, Object arg) {
		if (o instanceof BuyService) {
			BuyService buyService = (BuyService) o;
			OrderForm orderForm = (OrderForm) arg;
			// 原价 购多个
			// 折扣 主团购 传递 priceId
			// 子团购 传递 主订单号
			/*
			 * else if (orderForm.getOrderId() != null && orderForm.getOrderId()
			 * != 0) { Order order =
			 * orderRepository.findOne(orderForm.getOrderId()); if
			 * (order.getOrderType().ordinal() == OrderTypeEnum.tuanMaster
			 * .ordinal()) { orderForm.setTuan(true);
			 * orderForm.setOrderType(OrderTypeEnum.tuan);
			 * orderForm.setOrder(order); orderForm.setPrice(order.getPrice());
			 * } else { // 错误 }
			 * 
			 * }
			 */
			Order order = add(orderForm);
			buyService.setOrder(order);
		}
		if (o instanceof PayService) {
			PayService payService = (PayService) o;
			if (arg instanceof WeiXinNotifyForm) {
				WeiXinNotifyForm form = (WeiXinNotifyForm) arg;
				Order order = findByTradeNo(form.getOut_trade_no());
				if (form.getResult_code().equals("SUCCESS")) {
					if (form.getReturn_code().equals("SUCCESS")) {
						if (order.getPay().ordinal() == PayEnum.unPay.ordinal()) {// 假如未支付
							payService.setTreate(true);// 订单支付进行处理
							order.setStatus(OrderEnum.pending);
							order.setPayType(PayTypeEnum.weixin);
							order.setPayTypeTitle(PayTypeEnum.weixin.getTitle());
							order.setPay(PayEnum.payed);
							order.setPayTitle(PayEnum.payed.getTitle());

							super.edit(order);
						}
					}
				}
				payService.setOrder(order);

			}

		}
	}

	@Override
	public List<Order> findByUserId(Long userId) {
		OrderForm orderForm = new OrderForm();
		orderForm.setUserId(userId);
		return findByForm(orderForm);
	}

	public static String create_nonce_str() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.halberds.user.service.OrderService#getWxPayInfo(com.halberds.user.form.
	 * OrderForm) https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1
	 */
	@Transactional
	@Cacheable(value = "orderCache", key = "#form.getOrderId()")
	@Override
	public WxPayInfoForm getPayInfoByWx(OrderForm form) {
		String nonce = create_nonce_str();
		Order order = findById(form.getOrderId());
		if (order == null) {
			throw new NutException("订单[" + form.getOrderId() + "]不存在");
		}
		order.setPayType(PayTypeEnum.weixin);
		WxOrderForm wxOrderForm = new WxOrderForm();
		wxOrderForm.setAppid(Global.wxAppId);
		wxOrderForm.setMchId(Global.wxMchId);
		wxOrderForm.setNonce_str(nonce);
		wxOrderForm.setBody(order.getTitle());
		wxOrderForm.setAttach(order.getName());
		wxOrderForm.setOut_trade_no(order.getTradeNo());
		wxOrderForm.setTotal_fee("1");// + order.getAmount());
		wxOrderForm.setTrade_type(Global.wxTradeType);
		wxOrderForm.setNotify_url(Global.wxNotifyUrl);

		SortedMap<Object, Object> pareMap = new TreeMap<Object, Object>();
		pareMap.put("appid", Global.wxAppId);
		pareMap.put("mch_id", Global.wxMchId);
		pareMap.put("nonce_str", nonce);
		pareMap.put("body", order.getTitle());
		pareMap.put("attach", order.getName());
		pareMap.put("out_trade_no", order.getTradeNo());
		pareMap.put("total_fee", "1");// + order.getAmount());
		pareMap.put("trade_type", Global.wxTradeType);
		pareMap.put("notify_url", Global.wxNotifyUrl);
		String characterEncoding = "UTF-8";
		String sign = MD5Util.createSign(characterEncoding, pareMap,
				Global.wxPayKey);
		wxOrderForm.setSign(sign);
		WxPayVO wxPayVO = BeanMapper.map(wxOrderForm, WxPayVO.class);
		XStream xStream = new XStream(new XppDriver(new XmlFriendlyReplacer(
				"_-", "_")));
		xStream.autodetectAnnotations(true);
		String xml = xStream.toXML(wxPayVO);

		String url = WxGlobal.doGetAppToOrder();
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient httpClient = httpClientBuilder.build();
		logger.info("url:" + url);
		HttpPost httpPost = new HttpPost(url);// 121.41.75.104

		StringEntity entity = new StringEntity(xml, "utf-8");
		entity.setContentEncoding("UTF-8");

		httpPost.setEntity(entity);
		HttpResponse response;
		try {
			response = httpClient.execute(httpPost);
			String resData = EntityUtils
					.toString(response.getEntity(), "UTF-8");
			WxPayInfoForm wxPayInfoVO = XmlMapper.toBean(resData,
					WxPayInfoForm.class);
			//
			String nonceRes = create_nonce_str();
			int time = (int) (System.currentTimeMillis() / 1000);
			SortedMap<Object, Object> resultMap = new TreeMap<Object, Object>();
			resultMap.put("appid", wxPayInfoVO.getAppid());
			resultMap.put("partnerid", wxPayInfoVO.getMch_id());
			resultMap.put("prepayid", wxPayInfoVO.getPrepay_id());
			resultMap.put("package", "Sign=WXPay");
			resultMap.put("noncestr", nonceRes);
			resultMap.put("timestamp", time);
			String signResult = MD5Util.createSign(characterEncoding,
					resultMap, Global.wxPayKey);
			wxPayInfoVO.setNonce_str(nonceRes);
			wxPayInfoVO.setSign(signResult);
			wxPayInfoVO.setTimeStamp(time);
			return wxPayInfoVO;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 请求结束，返回结果
		return null;

	}

	@Autowired
	private FreemarkerUtil freemarkerUtil;
	@Autowired
	private AppConfig appConfig;
	/*
	 * gc.add(1,-1)表示年份减一.gc.add(2,-1)表示月份减一.gc.add(3.-1)表示周减一.gc.add(5,-1)表示天减一
	 */
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@CacheEvict(value = "orderCache", key = "#order.getId()")
	@Transactional
	@Override
	public String weiXinNotice(Order order, WeiXinNotifyForm notifyForm) {
		if (notifyForm.getResult_code().equals("SUCCESS")) {
			if (notifyForm.getReturn_code().equals("SUCCESS")) {
				 orderPayed(order);//boolean isOrderPay =
			}
		}
		return "SUCCESS";
	}

	@Transactional
	public boolean orderPayed(Order order) {
		if (order.getPay().ordinal() == PayEnum.unPay.ordinal()) {// 假如未支付
			order.setStatus(OrderEnum.pending);
			order.setPayType(PayTypeEnum.weixin);
			order.setPayTypeTitle(PayTypeEnum.weixin.getTitle());
			order.setPay(PayEnum.payed);
			order.setPayTitle(PayEnum.payed.getTitle());
			if (order.isTuan()) {// 团购
				if (order.isMaster()) { // 主团购
					MasterTuan masterTuan = masterTuanService
							.findByOrderId(order.getId());
					String httpPath = appConfig.getHttpPrix()
							+ masterTuanService.buildHtml(masterTuan);
					GregorianCalendar gc = new GregorianCalendar();
					Date currDate = new Date();
					gc.setTime(currDate);
					masterTuan.setBeginTime(gc.getTime());
					// masterTuan.setBeginTime(format.format(currDate));
					gc.add(5, 3);
					masterTuan.setShareUrl(httpPath);
					masterTuan.setShareTitle(order.getTitle());
					masterTuan.setEndTime(gc.getTime());
					// masterTuan.setEndTime(format.format(gc.getTime()));
					masterTuanService.edit(masterTuan);
				}
				// 计算是否满团
				// 生成我的团信息
				// freemarkerUtil.GenerateFile(form);
			}
			super.edit(order);
			orderInfoService.payed(order);
			return true;
		}
		return false;
	}

	@Transactional
	@Override
	public String noticeAdd(PayNotify payNotify) {
		payNotifyRepository.save(payNotify);
		switch (payNotify.getPayType()) {
		case alipay:
			break;
		case weixin:

			break;
		default:
			break;

		}

		return "SUCCESS";
	}

	public void aop() {
		logger.info("【注解-后置通知】:方法正常结束了");
	}
	@Override
	public Order findByTradeNo(String tradeNo) {
		return orderRepository.findByTradeNo(tradeNo);
	}

}
